package com.community.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.community.service.ResourceDownloadService;
import com.community.service.ResourceService;
import com.community.service.UserService;
import com.community.web.Common;

@SessionAttributes("myUid")
@Controller
public class ImageFileController {
	private static final Logger logger = LoggerFactory
			.getLogger(ImageFileController.class);

	@Autowired
	private UserService userService;
	@Autowired
	private ResourceDownloadService resourceDownloadService;
	@Autowired
	private ResourceService resourceService;

	private static String SAVE_UPLOAD_FILE_PATH;

	private static final String FILE_PATH = "resources" + File.separator
			+ "image" + File.separator;

	private static final ThreadLocal<SimpleDateFormat> yyyyMMddHHmmssSSS = new ThreadLocal<SimpleDateFormat>() {
		protected SimpleDateFormat initialValue() {
			return new SimpleDateFormat("yyyyMMddHHmmssSSS");
		}
	};

	private static final String[] fileTypes = new String[] { "gif", "jpg",
			"jpeg", "png", "bmp" };
	// private static final HashMap<String, String> extMap = new HashMap<String,
	// String>();
	// static {
	// extMap.put("image", "gif,jpg,jpeg,png,bmp");
	// extMap.put("flash", "swf,flv");
	// extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
	// extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
	// }
	// 最大文件大小
	private static final long MAX_SIZE = 5 * 1024 * 1024;

	@RequestMapping(value = "/upload", method = RequestMethod.POST, produces = { "application/json" })
	public @ResponseBody String upload(Model model, HttpServletRequest request,
			@ModelAttribute("myUid") Long myUid,
			@RequestParam("imgFile") MultipartFile multipartFile) {
		if (!multipartFile.isEmpty()) {
			if (SAVE_UPLOAD_FILE_PATH == null) {
				SAVE_UPLOAD_FILE_PATH = request.getServletContext()
						.getRealPath("/") + FILE_PATH;
				logger.info(SAVE_UPLOAD_FILE_PATH);
				File file = new File(SAVE_UPLOAD_FILE_PATH);
				if (!file.exists()) {
					file.mkdirs();
				}
			}
			// 检查文件大小
			if (multipartFile.getSize() > MAX_SIZE) {
				return getError("上传文件大小超过限制。").toJSONString();
			}
			// 检查扩展名
			String filename = multipartFile.getOriginalFilename();
			String fileExtension = filename
					.substring(filename.lastIndexOf(".") + 1);
			if (!Arrays.<String> asList(fileTypes).contains(fileExtension)) {
				return getError(
						"上传文件扩展名是不允许的扩展名。\n只允许" + Arrays.toString(fileTypes)
								+ "格式。").toJSONString();
			}

			filename = saveFile(multipartFile, fileExtension, myUid);
			if (filename != null) {
				JSONObject obj = new JSONObject();
				obj.put("error", 0);
				obj.put("url", Common.getBasePath(request) + "/" + FILE_PATH
						+ "/" + myUid + "/" + filename);
				return obj.toJSONString();
			}
		}
		return getError("上传文件失败。").toJSONString();
	}

	private JSONObject getError(String message) {
		JSONObject obj = new JSONObject();
		obj.put("error", 1);
		obj.put("message", message);
		return obj;
	}

	private String saveFile(MultipartFile multipartFile, String fileExtension,
			long uid) {
		String filename = yyyyMMddHHmmssSSS.get().format(new Date()) + "_"
				+ uid + "." + fileExtension;
		logger.info("filename={}", filename);
		BufferedOutputStream output = null;
		try {
			File file = new File(SAVE_UPLOAD_FILE_PATH + uid);
			if (!file.exists()) {
				file.mkdirs();
			}
			byte[] bytes = multipartFile.getBytes();
			output = new BufferedOutputStream(new FileOutputStream(new File(
					SAVE_UPLOAD_FILE_PATH + File.separator + uid, filename)));
			output.write(bytes);
			return filename;
		} catch (IOException e) {
			logger.error("{}", e);
		} finally {
			IOUtils.closeQuietly(output);
		}
		return null;
	}

	@RequestMapping(value = "/fileManager", method = RequestMethod.GET, produces = { "application/json" })
	public @ResponseBody String fileManager(Model model,
			HttpServletRequest request,
			@RequestParam(value = "order") String order,
			@RequestParam(value = "path") String path,
			@ModelAttribute("myUid") Long myUid) {
		if (SAVE_UPLOAD_FILE_PATH == null) {
			SAVE_UPLOAD_FILE_PATH = request.getServletContext()
					.getRealPath("/") + FILE_PATH;
			File file = new File(SAVE_UPLOAD_FILE_PATH);
			if (!file.exists()) {
				file.mkdirs();
			}
		}

		String rootPath = SAVE_UPLOAD_FILE_PATH + File.separator + myUid;
		File rootFile = new File(rootPath);
		if (!rootFile.exists()) {
			rootFile.mkdirs();
		}
		String rootUrl = Common.getBasePath(request) + "/" + FILE_PATH + "/"
				+ myUid + "/";
		// 根据path参数，设置各路径和URL
		String currentPath = rootPath + path;
		String currentUrl = rootUrl + path;
		String currentDirPath = path;
		String moveupDirPath = "";
		if (!"".equals(path)) {
			String str = currentDirPath.substring(0,
					currentDirPath.length() - 1);
			moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0,
					str.lastIndexOf("/") + 1) : "";
		}

		// 排序形式，name or size or type
		order = order.toLowerCase();

		// 不允许使用..移动到上一级目录
		if (path.indexOf("..") >= 0) {
			return getError("Access is not allowed.").toJSONString();
		}
		// 最后一个字符不是/
		if (!"".equals(path) && !path.endsWith("/")) {
			return getError("Parameter is not valid.").toJSONString();
		}
		// 目录不存在或不是目录
		File currentPathFile = new File(currentPath);
		if (!currentPathFile.isDirectory()) {
			return getError("Directory does not exist.").toJSONString();
		}

		// 遍历目录取的文件信息
		List<HashMap> fileList = new ArrayList<HashMap>();
		if (currentPathFile.listFiles() != null) {
			for (File file : currentPathFile.listFiles()) {
				HashMap<String, Object> hash = new HashMap<String, Object>();
				String fileName = file.getName();
				if (file.isDirectory()) {
					hash.put("is_dir", true);
					hash.put("has_file", (file.listFiles() != null));
					hash.put("filesize", 0L);
					hash.put("is_photo", false);
					hash.put("filetype", "");
				} else if (file.isFile()) {
					String fileExt = fileName.substring(
							fileName.lastIndexOf(".") + 1).toLowerCase();
					hash.put("is_dir", false);
					hash.put("has_file", false);
					hash.put("filesize", file.length());
					hash.put("is_photo", Arrays.<String> asList(fileTypes)
							.contains(fileExt));
					hash.put("filetype", fileExt);
				}
				hash.put("filename", fileName);
				hash.put("datetime",
						new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file
								.lastModified()));
				fileList.add(hash);
			}
		}

		if ("size".equals(order)) {
			Collections.sort(fileList, new SizeComparator());
		} else if ("type".equals(order)) {
			Collections.sort(fileList, new TypeComparator());
		} else {
			Collections.sort(fileList, new NameComparator());
		}
		JSONObject result = new JSONObject();
		result.put("moveup_dir_path", moveupDirPath);
		result.put("current_dir_path", currentDirPath);
		result.put("current_url", currentUrl);
		result.put("total_count", fileList.size());
		result.put("file_list", fileList);
		return result.toJSONString();
	}

	public class NameComparator implements Comparator {
		public int compare(Object a, Object b) {
			HashMap hashA = (HashMap) a;
			HashMap hashB = (HashMap) b;
			if (((Boolean) hashA.get("is_dir"))
					&& !((Boolean) hashB.get("is_dir"))) {
				return -1;
			} else if (!((Boolean) hashA.get("is_dir"))
					&& ((Boolean) hashB.get("is_dir"))) {
				return 1;
			} else {
				return ((String) hashA.get("filename"))
						.compareTo((String) hashB.get("filename"));
			}
		}
	}

	public class SizeComparator implements Comparator {
		public int compare(Object a, Object b) {
			HashMap hashA = (HashMap) a;
			HashMap hashB = (HashMap) b;
			if (((Boolean) hashA.get("is_dir"))
					&& !((Boolean) hashB.get("is_dir"))) {
				return -1;
			} else if (!((Boolean) hashA.get("is_dir"))
					&& ((Boolean) hashB.get("is_dir"))) {
				return 1;
			} else {
				if (((Long) hashA.get("filesize")) > ((Long) hashB
						.get("filesize"))) {
					return 1;
				} else if (((Long) hashA.get("filesize")) < ((Long) hashB
						.get("filesize"))) {
					return -1;
				} else {
					return 0;
				}
			}
		}
	}

	public class TypeComparator implements Comparator {
		public int compare(Object a, Object b) {
			HashMap hashA = (HashMap) a;
			HashMap hashB = (HashMap) b;
			if (((Boolean) hashA.get("is_dir"))
					&& !((Boolean) hashB.get("is_dir"))) {
				return -1;
			} else if (!((Boolean) hashA.get("is_dir"))
					&& ((Boolean) hashB.get("is_dir"))) {
				return 1;
			} else {
				return ((String) hashA.get("filetype"))
						.compareTo((String) hashB.get("filetype"));
			}
		}
	}

}
